package com.wanli.agent.homepage.adapter;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.wanli.agent.R;
import com.wanli.agent.utils.SPManager;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Author: HWC
 * Description: 服务商列表
 */
public class TipsMobileListAdapter extends RecyclerView.Adapter<TipsMobileListAdapter.ViewHolder> {

    private List<String> listsBeans;
    private Context context;
    private OnCallBackListener onCallBackListener;

    public TipsMobileListAdapter(List<String> listsBeans) {
        this.listsBeans = listsBeans;
    }

    public void setOnCallBackListener(OnCallBackListener onCallBackListener) {
        this.onCallBackListener = onCallBackListener;
    }

    @NonNull
    @Override
    public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int viewType) {
        context = viewGroup.getContext();
        View inflate = LayoutInflater.from(context).inflate(R.layout.item_hostory_list, viewGroup, false);
        ViewHolder viewHolder = new ViewHolder(inflate);
        return viewHolder;
    }

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        String dataBean = listsBeans.get(position);
        if (!TextUtils.isEmpty(dataBean)) {
            holder.tvName.setText(dataBean.split("_")[0]);
        } else {
            holder.tvName.setText("");
        }
        if (position == listsBeans.size() - 1) {
            holder.viewLine.setVisibility(View.GONE);
        } else {
            holder.viewLine.setVisibility(View.VISIBLE);
        }
        holder.itemView.setOnClickListener(v -> {
            onCallBackListener.onCallBack(dataBean);
        });
        holder.ivDelete.setOnClickListener(v -> {
            SPManager.getInstance().deleteSearchRecord(dataBean);
            listsBeans.remove(position);
            notifyDataSetChanged();
        });
    }

    @Override
    public int getItemCount() {
        return listsBeans.size() == 0 ? 0 : listsBeans.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {

        @BindView(R.id.tv_name)
        TextView tvName;
        @BindView(R.id.iv_delete)
        ImageView ivDelete;
        @BindView(R.id.view_line)
        View viewLine;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            ButterKnife.bind(this, itemView);
        }
    }

    public interface OnCallBackListener {
        void onCallBack(String data);
    }
}
